package com.wsd.smartcarwasher.controller;

import com.wsd.smartcarwasher.constans.Constant;
import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.domain.Partner;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.service.PartnerService;
import com.wsd.smartcarwasher.service.RedisService;
import com.wsd.smartcarwasher.service.WxService;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(tags = "微信相关相关接口")
@Controller
@CrossOrigin
public class WxController {
    private static final Logger logger = LoggerFactory.getLogger(WxController.class);

    @Resource
    private WxService wxService;

    @Resource
    private RedisService redisService;

    @Resource
    private PartnerService partnerService;

    /**
     * 查询用户小程序码
     *
     * @param request 请求
     * @return 返回小程序码服务器地址
     */
    @ApiOperation(value="查询用户的小程序码", notes = "微信相关", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/wx/wx_code", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getUserWxCode(HttpServletRequest request) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        if (StringUtils.isBlank(sessionId)) {
            return ReturnUtil.Error(ResultState.UNAUTHENTICATION_ERROR.getMsg());
        }
        return wxService.getWxACode(sessionId);
    }

    @ApiOperation(value="公众号获取用户授权", notes = "微信相关", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/wx/auth_code", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public void getUserAuthCode(HttpServletResponse response) {
        String redirectUrl = Constant.DOMAIN + "v1/wx/official_account_login";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo";
        url = url.replace("APPID", Constant.OFFICIAL_APP_ID).replace("REDIRECT_URI", redirectUrl);
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            logger.error("");
        }
    }
    /**
     * 运营端登录
     * @param code 小程序码
     * @param response 响应
     */
    @RequestMapping(value = "/v1/wx/official_account_login", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public void partnerLogin(@RequestParam(value = "code",required = false) String code, HttpServletResponse response) throws IOException {
        String redirectUrl = Constant.RUNNER_DOMAIN + "runner/#/404";
//        String redirectUrl = Constant.RUNNER_DOMAIN + "runner/#/login";

        if (StringUtils.isNotBlank(code)) {
            String openId = wxService.getOpenIdAndAuthAccessToken(code);

            if (StringUtils.isNotBlank(openId)) {
                String sessionId = StringUtil.getRandomUUID(Global.SESSIONID_PREFIX);
                redisService.put(sessionId, openId, 7200);
                response.setHeader(Global.AUTHORIZATION, sessionId);

                Partner partner = partnerService.getPartnerByOpenId(openId);
                if (partner == null) {
                    redirectUrl = Constant.RUNNER_DOMAIN + "runner/#/login?sessionId=" + sessionId;
                } else {
                    redirectUrl = Constant.RUNNER_DOMAIN + "runner/#/tabs/profit?sessionId=" + sessionId;
                }
            }
        }
        try {
            logger.info(redirectUrl);
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            logger.error("重定向redirectUrl:" + redirectUrl + "失败", e);
        }
    }


    //========================= new lyj = ========================
    //encryptedData, String iv
    @ApiOperation( value = "登录并且获取用户绑定手机号", notes = "登录并且获取用户绑定手机号",  produces = "application/json", response = ModelMap.class)
    @ApiImplicitParams({
            @ApiImplicitParam(  name = "sessionKey", value = "sessionKey", required = true,  dataType = "String"),
            @ApiImplicitParam(  name = "encryptedData", value = "encryptedData", required = true,  dataType = "String"),
            @ApiImplicitParam(  name = "iv", value = "iv", required = true,  dataType = "String"),
            @ApiImplicitParam(  name = "aUserId", value = "aUserId", required = false,  dataType = "String")
    })
    @RequestMapping(value = {"/v1/wx_login_by_mobile"},method = {RequestMethod.GET},produces = {"application/json; charset=utf-8"})
    @ResponseBody
    public ModelMap loginByWeiXinGetMobile(@RequestParam("sessionKey") String sessionKey,
                                           @RequestParam("encryptedData") String encryptedData,
                                           @RequestParam("iv") String iv,HttpServletRequest request
    ) {
        if(StringUtil.isEmpty(encryptedData) || StringUtil.isEmpty(iv) || StringUtil.isEmpty(sessionKey)){
            ReturnUtil.Error("参数不能为空 不能为空");
        }
        String aUserid = request.getParameter("aUserId");
        return  this.wxService.loginByWeiXinGetMobel(sessionKey,encryptedData,iv,aUserid);

    }

    @ApiOperation(
            value = "获取   SessionKey ",
            notes = "小程序-获取sessionKey",
            produces = "application/json",
            response = ModelMap.class
    )
    @ApiImplicitParam(
            name = "code",
            value = "code",
            required = false,
            dataType = "String"
    )
    @RequestMapping(
            value = {"/v1/wx/sessionKey"},
            method = {RequestMethod.GET},
            produces = {"application/json; charset=utf-8"}
    )
    @ResponseBody
    public ModelMap getSessionKey(@RequestParam String  code, HttpServletRequest request) {
         //String sessionId = request.getHeader("authorization");
         return  wxService.getSession_key(code);
    }


    /**
     * 查询用户的会员卡信息
     *
     * @return 用户会员卡信息
     */
    @ApiOperation(value="获取当前登录的用户id", notes = "小程序端用户会员卡信息", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/getUserId", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getUserId(HttpServletRequest request) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error(ResultState.GET_USER_INFO_FAILED.getMsg());
        }
        return ReturnUtil.Success("查询用户信息成功", user.getUserId());
    }
    /**
     * 查询用户的会员卡信息
     * @return 用户会员卡信息
     */
    @ApiOperation(value="小程序端获取用信息", notes = "小程序端获取用信息", produces = "application/json", response = ModelMap.class)
    @RequestMapping(value = "/v1/getMobile", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ModelMap getMobile(HttpServletRequest request) {
        String sessionId = request.getHeader(Global.AUTHORIZATION);
        UserInfo user = wxService.getUserInfoBySessionId(sessionId);
        if (user == null) {
            return ReturnUtil.Error("尚未登录");
        }
        //1013手机号登录要改
        if (user.getMobile() == null) {
            return ReturnUtil.ErrorMoblie("用户没有绑定手机号");
        }
        return ReturnUtil.Success("用户绑定手机号", user.getMobile());
    }
}
